import Request from 'luch-request';
// 开发huanj
export const apiBaseUrl = 'http://192.168.202.165:18080/app-api'
const http = new Request()

import * as LoginApi from '@/api/login'

http.setConfig((config) => { /* 设置全局配置 */
    config.header = {
        ...config.header,
    }
    return config
})

// 请求拦截
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
    config.baseURL = apiBaseUrl
    config.header = {
        ...config.header,
        Authorization: `Bearer ${uni.getStorageSync('token')}` || '',
    }
    return config
}, err => {
    return Promise.reject(err)
})
// 防止重复刷新标志位
let isRefreshing = false
// 重试队列，每一项将是一个待执行的函数形式
let requests = []

// 响应拦截
http.interceptors.response.use(
    async (response) => {
        const refreshToken = uni.getStorageSync('refreshToken')
        if (response) {
            let code = response.data.code
            if (code === 0) {
                // 正常状态
                return Promise.resolve(response.data.data)
            } else if (code === 401) {
                // 存在才刷新token
                if (refreshToken) {
                    const config = response.config
                    let newToken;
                    if (!isRefreshing) {
                        isRefreshing = true
                        await LoginApi.refreshToken(refreshToken).then(res => {
                            newToken = uni.setStorageSync('token', res.accessToken)
                            uni.setStorageSync('token', res.accessToken);
                            uni.setStorageSync('refreshToken', res.refreshToken);
                            requests.forEach((cb) => {
                                cb()
                            })
                            requests = []
                            return http.request(config)
                        }).catch((err) => {
                            // 令牌出错，退出登录
                            uni.clearStorageSync()
                            setTimeout(() => {
                                uni.reLaunch({
                                    url: '/pages/login/login'
                                });
                            }, 1000);
                            return Promise.reject(response)
                        }).finally(() => {
                            requests = []
                            isRefreshing = false
                        })
                    } else {
                        return new Promise((resolve) => {
                            requests.push((newToken) => {
                                config.header.Authorization = `Bearer ${newToken}` || ''
                                resolve(http.request(config))
                            })
                        })
                    }
                } else {
                    //  退出登录
                    uni.uToast.hide()
                    uni.uToast({
                        type: "error",
                        message: response.data.msg
                    })
                    uni.clearStorageSync()
                    setTimeout(() => {
                        uni.reLaunch({
                            url: '/pages/login/login'
                        });
                    }, 1000);
                    return Promise.reject(response)
                }

            } else {
                uni.uToast.hide()
                uni.uToast({
                    type: "error",
                    message: response.data.msg
                })
                return Promise.reject(response)

            }

        }
        return Promise.reject(response)
    },
    async (err) => {
        return Promise.reject(err)
    })

export default http

